#include "clock.h"
#include "ti_msp_dl_config.h"

volatile uint64_t tick_us;
volatile uint64_t start_time;

int8_t mspm0_delay_ms(uint32_t num_ms) {
  start_time = tick_us;
  while (tick_us - start_time < num_ms * 1000)
    ;
  return 0;
}

int8_t mspm0_get_clock_ms(uint32_t *count) {
  if (!count)
    return -1;
  count[0] = tick_us / 1000;
  return 0;
}
int8_t mspm0_get_clock_us(uint64_t *cnt) {
  if (!cnt)
    return -1;
  cnt[0] = tick_us;

  return 0;
}

int8_t mspm0_delay_us(uint32_t us) {
  start_time = tick_us;
  while (tick_us - start_time < us)
    ;

  // #define _1_US_CYCLE (CPUCLK_FREQ / 1000000)
  //   delay_cycles(us * _1_US_CYCLE);

  return 0;
}

void SysTick_Init(void) {
  NVIC_EnableIRQ(US_TIMER_INST_INT_IRQN); // 使能中断
  DL_Timer_startCounter(US_TIMER_INST);   // 启动定时器
}

void US_TIMER_INST_IRQHandler(void) {
  switch (DL_Timer_getPendingInterrupt(US_TIMER_INST)) {
  case DL_TIMERA_INTERRUPT_ZERO_EVENT:
    tick_us++;
    break;
  default:
    break;
  }
}
